package com.orange.core.validator;

import cn.hutool.core.util.StrUtil;
import com.orange.core.util.Constants;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

public class PasswordValidator implements ConstraintValidator<IsValidPassword, String> {

    private int min;
    private int max;

    @Override
    public void initialize(IsValidPassword annotation) {
        this.min = annotation.min();
        this.max = annotation.max();
        if (this.min < 1 || this.max < 1 || this.max < this.min) {
            throw new IllegalArgumentException("密码长度不能为负数");
        }
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StrUtil.isBlank(value)) {
            return false;
        }
        Pattern pattern = Pattern.compile(String.format(Constants.PASSWORD_RGX, min, max));
        return pattern.matcher(value).matches();
    }
}
